package com.syni.mdd.sjb.community.base.controller;

import com.syni.mdd.sjb.common.component.utils.common.utils.AppConfig;
import com.syni.mdd.sjb.community.base.config.QywxProperties;
import com.syni.mdd.sjb.community.base.service.WxCommunityAuthService;
import com.syni.mdd.sjb.community.base.utils.OAUtils;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.Map;

/**
 * @author wangbaitao
 * @version 1.0.0
 * <h>企业微信授权Controller</h>
 * @Date 2021/2/5
 **/
@RestController
@Log4j2
@EnableConfigurationProperties(QywxProperties.class)
@RequestMapping("/auth")
public class WxCommunityAuthController {

    private QywxProperties qywxProperties;
    @Autowired
    private WxCommunityAuthService wxCommunityAuthService;

    /**
     * 获取授权链接的二维码
     *
     * @param suiteId 应用id
     * @param userId  用户Id
     * @return 包含二维码地址的结果
     */
    @GetMapping("getQrCode")
    public Map<String, String> getQrCode(@RequestParam("userId") String suiteId,
                                         @RequestParam("userId") String userId) {
        return wxCommunityAuthService.getQrCode(suiteId, userId);
    }

    /**
     * app端授权跳转链接
     *
     * @param rp HttpServletResponse
     * @throws IOException io异常
     */
    @GetMapping("/connectToUser")
    public void connectToUser(HttpServletResponse rp) throws IOException {
        String redirect_uri = String.format(qywxProperties.getRegisterUrl(), OAUtils.getRegisterCode(), "test123456");
        log.info("turn url : {}", redirect_uri);
        rp.sendRedirect(redirect_uri);
    }

    /**
     * app端授权指令回调接口，用于接受state包含的用户id等自定义参数
     *
     * @param code  authCode
     * @param state 自定义参数体
     */
    @GetMapping("/connectRedirectUrl")
    public void connectRedirectUrl(@RequestParam("code") String code, @RequestParam("state") String state) {
        log.info("员工id（Code）:{}", code);
        log.info("数据宝用户id（state）:{}", state);
    }

    /**
     * PC端二维码连接
     *
     * @param code  authCode
     * @param state 自定义参数体
     */
    @GetMapping("/pcCode")
    public void pcCode(HttpServletResponse rp) throws IOException{
        String url = String.format("https://open.work.weixin.qq.com/wwopen/sso/3rd_qrConnect?appid=%s&redirect_uri=%s&state=state&usertype=admin"
                , AppConfig.getProperty("SuiteID"), URLEncoder.encode("http://dg.syni.com/sjbApi/community/base/auth/scanCode","utf-8"));
        rp.sendRedirect(url);

    }
}
